from user import models
from app01 import models as amodels
from django.shortcuts import render, redirect
from user.utils.form import SigninForm, SignupModelForm
import random

def signin(request):
    """ 登录 """
    if request.method == "GET":
        form = SigninForm()
        return render(request, 'signin.html', {'form': form})
    # POST
    form = SigninForm(data=request.POST)
    if form.is_valid():
        print(request.POST)
        user_obj = models.User.objects.filter(**form.cleaned_data).first()
        if not user_obj:
            form.add_error('password', '用户名或密码错误')  # 主动在某字段上显示错误信息
            return render(request, 'signin.html', {'form': form})
        # 用户名和密码正确
        # 网站生成随机字符串，写到用户浏览器的cookie中，再写入网站session中
        request.session['info'] = {'id': user_obj.id, 'name': user_obj.username}  # 网站session中:info为这个字典
        # session保存七天，即七天内免登录
        request.session.set_expiry(60 * 60 * 24 * 7)
        # request.session.set_expiry(10)
        # 登录成功自动跳转
        return redirect('/index/')
    return render(request, 'signin.html', {'form': form})


def signup(request):
    chalist = ['爱车达人','老司机','美女车手','狂飙车神','汽车维修']
    n = random.randint(0,4)
    if request.method == 'GET':
        form = SignupModelForm()
        return render(request, 'signup.html', {'form': form})
    # POST
    form = SignupModelForm(data=request.POST)

    infomation=request.POST
    u_name = infomation['username']
    pwd = request.POST.get('pwd')
    user = {
        'u_name': u_name,
        'password': pwd,
        'u_cha': chalist[n],
    }
    amodels.User.objects.create(**user)

    if form.is_valid():
        form.save()
        return redirect('/signin/')
    else:
        return render(request, 'signup.html', {'form': form})


def signout(request):
    request.session.clear()  # 清除当前用户的session
    return redirect('/index/')


def index(request):
    return render(request, 'index.html')
